package com.syeet.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syeet.common.utils.HttpUtils;
import com.syeet.common.utils.PageUtils;
import com.syeet.common.utils.Query;
import com.syeet.gulimall.member.dao.MemberDao;
import com.syeet.gulimall.member.dao.MemberLevelDao;
import com.syeet.gulimall.member.entity.MemberEntity;
import com.syeet.gulimall.member.entity.MemberLevelEntity;
import com.syeet.gulimall.member.exception.PhoneExistException;
import com.syeet.gulimall.member.exception.UsernameExistException;
import com.syeet.gulimall.member.service.MemberService;
import com.syeet.gulimall.member.vo.MemberLoginVo;
import com.syeet.gulimall.member.vo.MemberRegistVo;
import com.syeet.gulimall.member.vo.SocailUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired(required = false)
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册会员
     *
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        //设置会员默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        //检查手机号和用户名唯一
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        //密码要加密处理
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(vo.getPassWord());
        entity.setPassword(password);

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        memberDao.insert(entity);
    }

    /**
     * 检查手机号是否唯一
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    /**
     * 检查用户名是否唯一
     *
     * @param userName
     * @return
     */
    @Override
    public void checkUserNameUnique(String userName) throws UsernameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    /**
     * 用户登录
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (entity == null) {
            return null;
        } else {
            //则用户存在，将明文密码对比数据库密码
            final String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean flag = passwordEncoder.matches(password, passwordDb);
            if (flag) {
                return entity;
            } else {
                return null;
            }
        }
    }

    /**
     * 社交用户登录（登录和注册合并逻辑）
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(SocailUser vo) throws Exception {
        //判断当前用户是否已经注册过该系统
        String uid = vo.getUid();
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //该用户已经注册过系统
            MemberEntity updateEntity = new MemberEntity();
            updateEntity.setId(memberEntity.getId());
            updateEntity.setAccessToken(vo.getAccess_token());
            updateEntity.setExpiresIn(vo.getExpires_in());
            updateEntity.setCreateTime(new Date());
            baseMapper.updateById(updateEntity);

            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        } else {
            //没有查询到当前用户的记录，需注册一个账号
            MemberEntity regist = new MemberEntity();
            try {

                //通过微博的access_token获取微博用户信息
                Map<String, String> query = new HashMap<>();
                query.put("access_token", vo.getAccess_token());
                query.put("uid", vo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //成功获取到用户信息
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    //头像
                    String profileImageUrl = jsonObject.getString("profile_image_url");
                    //...
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                    regist.setHeader(profileImageUrl);
                    regist.setCreateTime(new Date());
                    //...
                }
            } catch (Exception e) {
            }
            regist.setSocialUid(vo.getUid());
            regist.setAccessToken(vo.getAccess_token());
            regist.setExpiresIn(vo.getExpires_in());
            baseMapper.insert(regist);
            return regist;

        }
    }

}